# coding=utf-8
#

import os

from datetime import datetime

from django.core.management.base import BaseCommand

from iminer.utils import check_pid

from iminer.stats.models import HiveonAlgo
from iminer.stats.models import HiveonCoin
from iminer.stats.models import HiveonMiner
from iminer.stats.models import HiveonGModel
from iminer.stats.models import HiveonGPUBrand

from iminer.stats.utils import get_hiveos_stats_data


from iminer.sm_log import getLogger


logger = getLogger("iminer.stats.management.commands.daily_get_hiveon_data")


class Command(BaseCommand):
    help = "每天抓取hiveon的数据"

    def handle(self, *args, **options):
        """ 每天抓取hiveon的数据 """
        task_name = "pid/daily_get_hiveon_data"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            today = datetime.now().date()

            data = get_hiveos_stats_data()

            key_mapper = {"amd_models": 1,
                          "nvidia_models": 2,
                          "asic_models": 3}

            # dict_keys(['algos', 'coins', 'miners', 'gpu_brands', 'amd_models', 'nvidia_models', 'asic_models'])
            for key, data in data.items():
                for cur_info in data:
                    if key == "algos":
                        HiveonAlgo(name=cur_info["name"], cur_date=today, amount=cur_info["amount"]).save()
                    elif key == "coins":
                        HiveonCoin(name=cur_info["name"], cur_date=today, amount=cur_info["amount"]).save()
                    elif key == "miners":
                        HiveonMiner(name=cur_info["name"], cur_date=today, amount=cur_info["amount"]).save()
                    elif key == "gpu_brands":
                        HiveonGPUBrand(name=cur_info["name"], cur_date=today, amount=cur_info["amount"]).save()
                    elif key in ["amd_models", "nvidia_models", "asic_models"]:
                        gtype = key_mapper[key]
                        HiveonGModel(name=cur_info["name"], cur_date=today, gtype=gtype, amount=cur_info["amount"]).save()
